package com.shenghuozhushou.fragments;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.shenghuozhushou.R;
import com.shenghuozhushou.gson.Forecast;
import com.shenghuozhushou.gson.Weather;
import com.shenghuozhushou.news.News;
import com.shenghuozhushou.news.RequestNewsData;
import com.shenghuozhushou.util.HttpUtil;
import com.shenghuozhushou.util.Utility;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherFragment extends Fragment {
    private View view;
    // 设置 public 供 ChooseAreaFragment 访问：
    public DrawerLayout drawerLayout;
    // 设置 public 供 ChooseAreaFragment 访问：
    public SwipeRefreshLayout swipeRefresh;
    private ScrollView weatherLayout;
    private ImageButton navButton;
    // 设置 public 供 ChooseAreaFragment 访问：
    public ImageButton toTopButton;
    private TextView updateTime;
    private TextView locationTitle;
    private TextView degreeText;
    private TextView weatherInfoText;
    private LinearLayout forecastLayout;
    private TextView aqiText;
    private TextView pm25Text;
    private TextView comfortText;
    private TextView carWashText;
    private TextView sportText;
    // 新闻模块：
    private List<News> newsList;
    // private ListView newsListView;
    private NewsHandler newsHandler = new NewsHandler();
    // private NewsAdapter newsAdapter = new NewsAdapter();
    private LinearLayout newsLayout;
    // 设置 public 供 ChooseAreaFragment 访问：
    public String mWeatherId;
    private Boolean firstEntry = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_weather, container, false);
        drawerLayout = (DrawerLayout) view.findViewById(R.id.drawer_layout);
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        swipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
        weatherLayout = (ScrollView) view.findViewById(R.id.weather_layout);
        navButton = (ImageButton) view.findViewById(R.id.nav_button);
        navButton.setOnClickListener(v -> {
            toTopButton.setVisibility(View.GONE);
            drawerLayout.openDrawer(GravityCompat.END);
        });
        toTopButton = (ImageButton) view.findViewById(R.id.to_top_button);
        toTopButton.setOnClickListener(v -> weatherLayout.fullScroll(ScrollView.FOCUS_UP));
        updateTime = (TextView) view.findViewById(R.id.update_time);
        locationTitle = (TextView) view.findViewById(R.id.location_title);
        degreeText = (TextView) view.findViewById(R.id.degree_text);
        weatherInfoText = (TextView) view.findViewById(R.id.weather_info_text);
        forecastLayout = (LinearLayout) view.findViewById(R.id.forecast_layout);
        aqiText = (TextView) view.findViewById(R.id.aqi_text);
        pm25Text = (TextView) view.findViewById(R.id.pm25_text);
        comfortText = (TextView) view.findViewById(R.id.comfort_text);
        carWashText = (TextView) view.findViewById(R.id.car_wash_text);
        sportText = (TextView) view.findViewById(R.id.sport_text);
        // newsListView = (ListView) view.findViewById(R.id.news_list);
        newsLayout = (LinearLayout) view.findViewById(R.id.news_layout);

        // 设置刷新事件监听：
        swipeRefresh.setOnRefreshListener(() -> {
            requestWeather(mWeatherId);
            RequestNewsData();
        });
        // swipeRefresh.setColorSchemeResources(com.google.android.material.R.color.design_default_color_primary);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
        String weatherString = prefs.getString("weather", null);
        if (firstEntry && weatherString == null) {
            locationTitle.setText("请选择地点！");
            drawerLayout.openDrawer(GravityCompat.END);
        } else if (firstEntry) {
            Weather weather = Utility.handleWeatherResponse(weatherString);
            mWeatherId = weather.basic.weatherId;
            requestWeather(mWeatherId);
        } else if (weatherString != null) {
            // 有缓存时直接解析天气数据：
            Weather weather = Utility.handleWeatherResponse(weatherString);
            mWeatherId = weather.basic.weatherId;
            showWeatherInfo(weather);
        }
        RequestNewsData();

        return view;
    }

    // 根据天气 id 请求城市天气信息：
    public void requestWeather(final String weatherId) {
        toTopButton.setVisibility(View.VISIBLE);
        String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=bc0418b57b2d4918819d3974ac1285d9";
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                final Weather weather = Utility.handleWeatherResponse(responseText);
                getActivity().runOnUiThread(() -> {
                    if (weather != null && "ok".equals(weather.status)) {
                        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getContext()).edit();
                        editor.putString("weather", responseText);
                        editor.apply();
                        mWeatherId = weather.basic.weatherId;
                        showWeatherInfo(weather);
                    } else {
                        Toast.makeText(getContext(), "获取天气信息失败", Toast.LENGTH_SHORT).show();
                    }
                    swipeRefresh.setRefreshing(false);
                });
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                getActivity().runOnUiThread(() -> {
                    Toast.makeText(getContext(), "获取天气信息失败", Toast.LENGTH_SHORT).show();
                    swipeRefresh.setRefreshing(false);
                });
            }
        });
    }

    // 处理并展示 Weather 实体类中的数据：
    private void showWeatherInfo(Weather weather) {
        String provinceName = weather.basic.adminArea;
        String cityName = weather.basic.parentCity;
        String countyName = weather.basic.location;
        String degree = weather.now.temperature + "℃";
        String weatherInfo = weather.now.more.info;
        updateTime.setText("上次更新：" + weather.basic.update.updateTime);
        // 显示选中的地点：
        if (provinceName.equals(cityName)) {
            locationTitle.setText(cityName + " " + countyName);
        } else {
            locationTitle.setText(provinceName + " " + cityName + " " + countyName);
        }
        degreeText.setText(degree);
        weatherInfoText.setText(weatherInfo);
        showWeatherImage(weatherInfo);
        forecastLayout.removeAllViews();
        for (Forecast forecast : weather.forecastList) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.forecast_item, forecastLayout, false);
            TextView dateText = (TextView) view.findViewById(R.id.date_text);
            TextView infoText = (TextView) view.findViewById(R.id.info_text);
            TextView maxText = (TextView) view.findViewById(R.id.max_text);
            TextView minText = (TextView) view.findViewById(R.id.min_text);
            dateText.setText(forecast.date);
            infoText.setText(forecast.more.info);
            maxText.setText(forecast.temperature.max);
            minText.setText(forecast.temperature.min);
            forecastLayout.addView(view);
        }
        if (weather.aqi != null) {
            aqiText.setText(weather.aqi.city.aqi);
            pm25Text.setText(weather.aqi.city.pm25);
        }
        String comfort = "舒适度：" + weather.suggestion.comfort.info;
        String carWash = "洗车指数：" + weather.suggestion.carWash.info;
        String sport = "运行建议：" + weather.suggestion.sport.info;
        comfortText.setText(comfort);
        carWashText.setText(carWash);
        sportText.setText(sport);
        weatherLayout.setVisibility(View.VISIBLE);

    }

    private void showWeatherImage(String weatherInfo) {
        ImageView imageView = (ImageView) view.findViewById(R.id.weather_image);
        // 获取当前系统时间：
        Calendar calendar;
        calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        boolean isAM = calendar.get(Calendar.AM_PM) == Calendar.PM;
        int Hour = isAM ? calendar.get(Calendar.HOUR) + 12 : calendar.get(Calendar.HOUR);
        switch (weatherInfo) {
            case "暴雪":
            case "大雪":
            case "中雪":
            case "小雪":
                imageView.setImageResource(R.drawable.weather_xue);
                break;
            case "暴雨":
            case "大雨":
            case "中雨":
                imageView.setImageResource(R.drawable.weather_da_yu);
                break;
            case "小雨":
            case "阵雨":
                imageView.setImageResource(R.drawable.weather_xiao_yu);
                break;
            case "雷阵雨":
                imageView.setImageResource(R.drawable.weather_lei_zhen_yu);
                break;
            case "多云":
            case "多云转阴":
            case "阴":
                imageView.setImageResource(R.drawable.weather_yin);
                break;
            case "多云转晴":
                if (Hour >= 18) imageView.setImageResource(R.drawable.weather_night_qingzhuanduoyun);
                else imageView.setImageResource(R.drawable.weather_night_qingzhuanduoyun);
                break;
            case "晴":
                if (Hour >= 18) imageView.setImageResource(R.drawable.weather_night_qing);
                else imageView.setImageResource(R.drawable.weather_qing);
                break;
            case "雾":
                imageView.setImageResource(R.drawable.weather_wu);
                break;
        }
    }

    private class NewsHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0){
                newsList = (List<News>)msg.obj;
                // newsListView.setAdapter(newsAdapter);
                newsLayout.removeAllViews();
                for (News news : newsList) {
                    View view = LayoutInflater.from(getContext()).inflate(R.layout.news_item, newsLayout, false);
                    TextView newsTitle = (TextView) view.findViewById(R.id.news_title);
                    TextView newsUrl = (TextView) view.findViewById(R.id.news_url);
                    newsTitle.setText(news.getTitle());
                    newsUrl.setText(news.getUrl());
                    newsTitle.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Uri uri = Uri.parse(newsUrl.getText().toString());
                            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                            startActivity(intent);
                        }
                    });
                    newsLayout.addView(view);
                }
            }
        }
    }

//    public class NewsAdapter extends BaseAdapter {
//
//        @Override
//        public int getCount() {
//            return newsList.size();
//        }
//
//        @Override
//        public Object getItem(int position) {
//            return newsList.get(position);
//        }
//
//        @Override
//        public long getItemId(int position) {
//            return position;
//        }
//
//        @Override
//        public View getView(int position, View convertView, ViewGroup parent) {
//            TextView titleText;
//            News news = (News) getItem(position);
//            if (convertView == null) {
//                convertView = getLayoutInflater().inflate(R.layout.news_item, null);
//                titleText = (TextView) convertView.findViewById(R.id.news_title);
//                convertView.setTag(titleText);
//            } else {
//                titleText = (TextView) convertView.getTag();
//            }
//            titleText.setText(news.getTitle());
//            return convertView;
//        }
//    }

    private void RequestNewsData(){
        HttpUtil.sendOkHttpRequest("https://way.jd.com/jisuapi/get?channel=头条&num=10&start=0&appkey=0d06c61b38f391b2ff3aeaad09bf8661",
            new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                    getActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "获取新闻列表失败", Toast.LENGTH_SHORT).show();
                        swipeRefresh.setRefreshing(false);
                    });
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    String newsJson = response.body().string();
                    RequestNewsData newsData = new Gson().fromJson(newsJson, RequestNewsData.class);
                    Message message = new Message();
                    message.what = 0;
                    message.obj = newsData.getResult().getResult().getList();
                    newsHandler.sendMessage(message);
                }
            });
    }
}